#include<stdio.h>
#include<stdlib.h>
#include<stdarg.h>
#include<math.h>
#include"util.h"
#include"symbol.h"
#include"table.h"

/*
@detail 本算法是由于在开源项目SDBM（一种简单的数据库引擎）中被应用而得名.
它与BKDRHash思想一致，只是种子不同而已。  
*/
static unsigned symhash(char* sym)
{
	unsigned int hash = 0;
	char *s;
	for(s=sym;*s;s++)
					hash = hash*65599 + *s;
	return hash;
}

void yyerror(char* s, ...)
{
	va_list ap;
	va_start(ap, s);//读取栈中的不定参数

	fprintf(stderr, "%d: error: ", yylineno);
	vfprintf(stderr, s, ap);			
	fprintf(stderr, "\n");
}

struct symbol* newSymbol(char* name, struct symbol* next)
{
	struct symbol* ptr = (struct symbol* )sec_malloc(sizeof(struct symbol));
	ptr->name = strdup(name);
	ptr->next = next;
	return ptr;
}


struct symbol* insertSymbol(char* name)
{
	unsigned int pos = symhash(name) % TABLESIZE;
	hashtable[pos] = newSymbol(name, hashtable[pos]);
	return hashtable[pos];
}

struct symbol* lookupSymbol(char* name)
{
	unsigned int pos = symhash(name) % TABLESIZE;
	struct symbol* s= hashtable[pos];
	while(s!=NULL){
		if(strcmp(name, s->name) == 0)
						return s;
		s = s->next;
	}
	return NULL;
}

void popSymbol(char* name)
{
	unsigned int pos = symhash(name) % TABLESIZE;
	struct symbol* s = hashtable[pos];
	struct symbol* next = s->next;
	if(s==NULL)
		return ;
	free(s);
	hashtable[pos] = next;
}

static struct symbol marksym = {"<mark>", NULL};

void* Symtable_lookup(struct table* t, struct symbol* sym)
{
	return table_lookup(t, sym);	
}
void Symtable_insert(struct table* t, struct symbol* key, void* value)
{
	table_insert(t, key, value);
}

void begin_Scope(struct table* t)
{
	Symtable_insert(t, &marksym, NULL);
}
void end_Scope(struct table* t)
{
	struct symbol* ptr;
	do{
		ptr = table_pop(t);
	}while( ptr != &marksym);
}

